package com.xuzhiguang.light.gateway.core.filter.factory;

import com.xuzhiguang.light.gateway.common.request.GatewayRequest;
import com.xuzhiguang.light.gateway.common.utils.StringUtils;
import com.xuzhiguang.light.gateway.core.context.GatewayContextConstant;
import com.xuzhiguang.light.gateway.core.filter.GatewayFilter;
import com.xuzhiguang.light.gateway.core.filter.GatewayFilterConfig;
import lombok.Data;

import java.net.URI;

/**
 * @author xuzhiguang
 */
public class StripPrefixGatewayFilterFactory extends AbstractGatewayFilterFactory<StripPrefixGatewayFilterFactory.Config> {

    public StripPrefixGatewayFilterFactory() {
        super(StripPrefixGatewayFilterFactory.Config.class);
    }

    @Override
    public GatewayFilter apply(StripPrefixGatewayFilterFactory.Config config) {

        return (context, chain) -> {
            GatewayRequest request = context.getRequest();
            String path = request.getURI().getRawPath();
            String[] originalParts = StringUtils.tokenizeToStringArray(path, "/");

            // 除去不需要的层
            StringBuilder newPath = new StringBuilder("/");
            for (int i = 0; i < originalParts.length; i++) {
                if (i >= config.getParts()) {

                    if (newPath.length() > 1) {
                        newPath.append('/');
                    }
                    newPath.append(originalParts[i]);
                }
            }

            // 如果结尾是 / , 在新 path 中加上 /
            if (newPath.length() > 1 && path.endsWith("/")) {
                newPath.append('/');
            }

            URI newUri = request.getURI().resolve(newPath.toString());
            context.putAttribute(GatewayContextConstant.REQUEST_URI_ATTR, newUri);

            chain.doFilter(context);
        };
    }


    @Data
    public static class Config implements GatewayFilterConfig {

        private int parts = 1;

    }
}
